package com.example.demo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.IPUtils;
import com.example.demo.util.RequestDto;
import com.example.demo.util.itfcheck.ItfCheckUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Aspect
public class TestAspect {

    @Pointcut("execution(* com.example.controller.*.*(..)))")
    public void executServer() {
    }

    @Before("executServer()")
    public void before() {
        System.out.println("--------------------before");
    }

    @After("executServer()")
    public void after() {
        System.out.println("-------after");
    }

    @Around("executServer()")
    public Object around (ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        String ip = IPUtils.getRealIP(request);//获取IP
        if (!"192.168.101.44".equals(ip)) {
            return  "IP 被拦截下来了！";
        }

        Object[] objs = pjp.getArgs(); //获取请求参数
        RequestDto requestDto = (RequestDto) objs[0];
        Long inTime = requestDto.getTimestamp();
        String sysCode = requestDto.getPartner();
        String mesgId = requestDto.getMesgId();
        String md5key = "abdcaaageff";  //作为MD5加密的字符串

        String sign = DigestUtils.md5Hex(sysCode + requestDto.getContent() + requestDto.getKey() + requestDto.getTimestamp() + md5key);
        if(!sign.equals(requestDto.getSign())) {
            return "验签失败";
        }
        String privateKey = "sqsqwqeqweqweqweqe"; //生成公私钥的私钥

        String data = ItfCheckUtil.decryption(requestDto,privateKey);// 解密出来的明文
        requestDto.setData(data);

        Object proceed = pjp.proceed();
        System.out.println(JSONObject.toJSONString(proceed));
        return proceed;
    }


    private String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

}
